package so.sao.shop.supplier.service.app.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import so.sao.shop.supplier.config.Constant;
import so.sao.shop.supplier.dao.ParameterDao;
import so.sao.shop.supplier.dao.app.AppApplyForServiceDao;
import so.sao.shop.supplier.domain.Parameter;
import so.sao.shop.supplier.pojo.Result;
import so.sao.shop.supplier.pojo.input.AppApplyForServiceInput;
import so.sao.shop.supplier.pojo.input.ServiceLogisticsInput;
import so.sao.shop.supplier.pojo.output.AppApplyForServiceOutput;
import so.sao.shop.supplier.pojo.vo.RefuseOrderImgVo;
import so.sao.shop.supplier.service.app.AppApplyForServiceService;
import so.sao.shop.supplier.util.DateUtil;
import so.sao.shop.supplier.util.Ognl;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 *<p>Version:  </p>
 *<p>Title: AppApplyForServiceServiceImpl</p>
 *<p>Description: app申请售后ServiceImpl</p>
 *@author: hanchao
 *@Date: Created in 2017/11/27 10:38
 */
@Service
public class AppApplyForServiceServiceImpl implements AppApplyForServiceService {
    @Autowired
    private AppApplyForServiceDao appApplyForServiceDao;
    @Autowired
    private ParameterDao parameterDao;
    /**
     * 根据detailsId查询退货退款/换货详情
     * @param detailsId
     * @return Result
     */
    @Override
    public Result searchApplicationDetail(Long detailsId) {
        AppApplyForServiceOutput appApplyForServiceOutput =  appApplyForServiceDao.searchApplicationDetail(detailsId);
        List<RefuseOrderImgVo> refuseOrderImgVos = appApplyForServiceDao.searchRefuseOrderImgs(detailsId);
        appApplyForServiceOutput.setRefuseOrderImgVos(refuseOrderImgVos);
        return Result.success(Constant.MessageConfig.MSG_SUCCESS,appApplyForServiceOutput);
    }
    /**
     * 退货退款/换货申请售后
     * @param appApplyForServiceInput
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateDetailsItemInformation(AppApplyForServiceInput appApplyForServiceInput) {
        /**
         * 1.子订单所属的大订单状态为已收货状态才能申请售后
         * 2.上传凭证照片不能超过3张
         * 3.收到货超过5天不能申请售后
         * 4.一个SKU只能申请一次
         * 5.生成退款/换货单号
         * 6.修改订单状态为申请退款，更新时间applyForTime
         */
        //根据detailsId查询子单以及所属的大订单
        AppApplyForServiceOutput appApplyForServiceOutput = appApplyForServiceDao.findDetailsItemInformation(appApplyForServiceInput.getDetailsId());
        //1.子订单所属的大订单状态为已收货状态才能申请售后
        if (!Constant.OrderStatusConfig.ORDER_RECEIVED.equals(appApplyForServiceOutput.getOrderStatus())) {
            return Result.fail(Constant.MessageConfig.NO_SERVICE);
        }
        //2.上传凭证照片不能超过3张
        if (null != appApplyForServiceInput.getRefuseOrderImgVos() && appApplyForServiceInput.getRefuseOrderImgVos().size() > 3) {
            return Result.fail(Constant.MessageConfig.OUT_OF_NUMBER);
        }
        List<Parameter> parameters = parameterDao.selectByKey("service_time");
        String days = parameters.get(0).getParameterValue();
        int day = Integer.valueOf(days);
        Date today = DateUtil.stringToDate(null);
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(appApplyForServiceOutput.getOrderReceiveTime());
        rightNow.add(Calendar.DAY_OF_YEAR, day);//日期加5天
        Date afterServiceToday = rightNow.getTime();
        boolean flag = today.before(afterServiceToday);
        //3.收到货超过5天不能申请售后
        if (!flag) {
            return Result.fail(Constant.MessageConfig.OUT_OF_DATE);
        }
        //4.一个SKU只能申请一次
        if (!Ognl.isEmpty(appApplyForServiceOutput.getType())) {
            return Result.fail(Constant.MessageConfig.REPEAT);
        }
        //5.生成退款/换货单号
        Integer orderNum = appApplyForServiceDao.countOrderNumByOrderId(appApplyForServiceOutput.getOrderId()) + 1;
        String returnNumber = appApplyForServiceOutput.getOrderId() + "-" + orderNum;
        appApplyForServiceInput.setReturnNumber(returnNumber);
        //6.修改订单状态为申请退款，更新时间applyForTime
        appApplyForServiceInput.setStatus(Constant.OrderDetailsStatusConfig.APPLYFORING);
        appApplyForServiceInput.setApplyForTime(new Date());
        // 售后申请数据数据入库：purchase_item
        appApplyForServiceDao.insertApplicationContent(appApplyForServiceInput);
        // 上传凭证照片数据入库：refuse_order_img
        List<RefuseOrderImgVo> refuseOrderImgVoList = new ArrayList<RefuseOrderImgVo>();
        if (null != appApplyForServiceInput.getRefuseOrderImgVos() && appApplyForServiceInput.getRefuseOrderImgVos().size() > 0) {
            for (int i = 0; i < appApplyForServiceInput.getRefuseOrderImgVos().size(); i++) {
                RefuseOrderImgVo refuseOrderImgVo = new RefuseOrderImgVo();
                refuseOrderImgVo.setOrderId(appApplyForServiceOutput.getOrderId());
                refuseOrderImgVo.setDetailsId(appApplyForServiceInput.getDetailsId());
                refuseOrderImgVo.setUrl(appApplyForServiceInput.getRefuseOrderImgVos().get(i).getUrl());
                refuseOrderImgVo.setMinImgUrl(appApplyForServiceInput.getRefuseOrderImgVos().get(i).getMinImgUrl());
                refuseOrderImgVo.setSize(appApplyForServiceInput.getRefuseOrderImgVos().get(i).getSize());
                refuseOrderImgVo.setFileName(appApplyForServiceInput.getRefuseOrderImgVos().get(i).getFileName());
                refuseOrderImgVo.setCreateTime(new Date());
                refuseOrderImgVoList.add(refuseOrderImgVo);
            }
            appApplyForServiceDao.insertRefuseOrderImg(refuseOrderImgVoList);
        }
            return Result.success(Constant.MessageConfig.MSG_SUCCESS);
    }

    /**
     * 拒收/换货退换退款- 新增售后物流信息
     * @param serviceLogisticsInput
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insertLogisticsInformation( ServiceLogisticsInput serviceLogisticsInput ){
        //售后类型(0拒收 1退换货)
        Integer type = serviceLogisticsInput.getType();
        //主订单状态
        Integer orderStatus = 0;
        //子订单详情（子订单状态）
        AppApplyForServiceOutput appApplyForServiceOutput = null;
        //物流售后类型(0.门店发货,1.供应商发货)
        serviceLogisticsInput.setLogisticsType(Constant.ServiceLogisticsType.logisticsType_STORE );
        //拒收时必须有OrderId 0拒收
        if(type.equals(Constant.ApplyForServiceType.TYPE_REJECT)){
            if(StringUtils.isEmpty(serviceLogisticsInput.getOrderId())){
                return Result.fail(Constant.MessageConfig.PARAMETER_ABNORMITY);
            }
            serviceLogisticsInput.setDetailsId(null);
            //根据主订单id查询主订单状态 10审核通过
            orderStatus =  appApplyForServiceDao.searchApplicationDetailByOrderId(serviceLogisticsInput.getOrderId());
        }
        //退换货时必须有DetailsId 1退换货
        if(type.equals(Constant.ApplyForServiceType.TYPE_RETURNANDEXCHANGE)) {
            if (StringUtils.isEmpty(serviceLogisticsInput.getDetailsId())) {
                return Result.fail(Constant.MessageConfig.PARAMETER_ABNORMITY);
            }
            serviceLogisticsInput.setOrderId(null);
            //根据detailsId查询退货退款/换货详情(子订单状态)
            appApplyForServiceOutput = appApplyForServiceDao.searchApplicationDetail(serviceLogisticsInput.getDetailsId());
        }
        //type==0 整单拒收，供应商审核后，更新主订单订单状态和退回商品时间
        if(type.equals(Constant.ApplyForServiceType.TYPE_REJECT) && Constant.OrderStatusConfig.EXAMINATION_PASSED.equals(orderStatus)){
            appApplyForServiceDao.insertLogisticsInformation( serviceLogisticsInput );
            appApplyForServiceDao.updataPurchaseStatusByOrderId(Constant.OrderStatusConfig.REFUNDING,new Date(),serviceLogisticsInput.getOrderId());
            return Result.success(Constant.MessageConfig.MSG_SUCCESS);
        }
        // type==1 退换货，供应商审核后，更新子订单订单状态和退回商品时间
        if(type.equals(Constant.ApplyForServiceType.TYPE_RETURNANDEXCHANGE) && Constant.OrderDetailsStatusConfig.PASSED .equals(appApplyForServiceOutput.getStatus())){
            Integer status = Constant.OrderDetailsStatusConfig.RETURNOREXCHANGE;
            appApplyForServiceDao.insertLogisticsInformation( serviceLogisticsInput );
            appApplyForServiceDao.updataPurchaseItem(status,new Date(),serviceLogisticsInput.getDetailsId());
            return Result.success(Constant.MessageConfig.MSG_SUCCESS);
        }
        return Result.fail(Constant.MessageConfig.MSG_FAILURE);
    }

    /**
     * 根据detailsId查询门店退换货物流信息
     * @param detailsId
     * @return Result
     */
    @Override
    public Result searchLogisticsInformation(Long detailsId) {
        /**
         * 1.根据物流售后类型logisticsType(0.门店发货,1.供应商发货)判断是退货还是换货
         * 2.根据配送方式logisticsShipMethod判断是供应商自取还是物流公司配送
         */
        return Result.success(Constant.MessageConfig.MSG_SUCCESS,appApplyForServiceDao.searchLogisticsInformation(detailsId));
    }
}